﻿using System.Collections.ObjectModel;
using System.ComponentModel;
using estoque.Model;

namespace estoque.ViewModel
{
    public class RepositoryVM : INotifyPropertyChanged
    {
        private static RepositoryVM center;

        public static RepositoryVM Center
        {
            get
            {
                if (RepositoryVM.center == null)
                {
                    Repository repository = Repository.LoadFromXml();
                    RepositoryVM.center = new RepositoryVM(repository);
                }

                return RepositoryVM.center;
            }
        }

        private Repository repository;

        public event PropertyChangedEventHandler PropertyChanged;

        public UserInterfaceStuff UIStuff { get; private set; }

        public ObservableCollection<ScenarioVM> Scenarios { get; private set; }

        private RepositoryVM(Repository repository)
        {
            this.repository = repository;
            this.UIStuff = new UserInterfaceStuff();
            this.Scenarios = ConvertAllObjectsToViewModels();
        }

        public void Save()
        {
            this.repository.SaveToXml();
        }

        public void AddTask(ScenarioVM parent, string text)
        {
            parent.Tasks.Add(new TaskVM(text));
            Tracer.AddDatabaseInformation("New Task generated.");
        }

        private ObservableCollection<ScenarioVM> ConvertAllObjectsToViewModels()
        {
            ObservableCollection<ScenarioVM> scenarios = new ObservableCollection<ScenarioVM>();

            foreach (var item in this.repository.Scenarios)
            {
                scenarios.Add(new ScenarioVM(item));

                foreach (var subItem in item.Tasks)
                {
                    scenarios[scenarios.Count - 1].Tasks.Add(new TaskVM(subItem));
                }
            }

            return scenarios;
        }

        internal void InvokePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler temp = this.PropertyChanged;
            if (temp != null)
            {
                temp(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public void Sort()
        {
            foreach (var item in this.Scenarios)
            {
                item.Tasks.Sort(player => player.TaskPriority);
            }
        }
    }
}